import time

from selenium import webdriver
from selenium.common import WebDriverException, InvalidArgumentException, NoSuchElementException
from selenium.webdriver.common.by import By


class Base:
    def __init__(self, browser):
        if browser == 'chrome':
            self.driver = webdriver.Chrome()
        elif browser == 'firefox':
            self.driver = webdriver.Firefox()
        elif browser == 'edge':
            self.driver = webdriver.Edge()
        else:
            print('不支持该浏览器')
            self.driver = None

    def get(self, url):
        try:
            self.driver.get(url)
        except(InvalidArgumentException, WebDriverException):
            print('输入网址不正确')

    def find_element(self, locator):
        try:
            return self.driver.find_element(*locator)
        except NoSuchElementException:
            print('元素定位失败')

    def click(self, locator):
        element = self.find_element(locator)
        if element is not None:
            element.click()
        else:
            print("元素定位失败")

    def send_keys(self, locator, value):
        element = self.find_element(locator)
        return self.driver.send_keys()
        # if element is not None:
        #     element.send_ksys()
        # else:
        #     print("写入失败")


    def method(self):
        self.driver.back()
        self.driver.refresh()
        self.driver.close()
        self.driver.forward()


    #获取元素属性
    def get_attrbute(self,locator, value):
        element = self.find_element(locator)
        if element is not None:
             return element.get_attribut(value)
        else:
            print("元素定位失败")

    def quit(self, seconds=3):
        time.sleep(seconds)
        self.driver.quit()


if __name__ == '__main__':
    l1 = Base('chrome')
    l1.get('https://baidu.com')
    l1.find_element((By.ID, "kw"))
    l1.get_attrbute(By.NAME,'username')
    # l1.send_keys()
    l1.quit()
